package com.buynow.cctapi.web;

import com.buynow.cctapi.constant.PaginatedResult;
import com.buynow.cctapi.util.db.DbBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.util.List;
import java.util.Map;

import static com.buynow.cctapi.util.db.DbBuilder.getCount;

/**
 * Created by Administrator on 2017-06-04.
 */
@RestController
@RequestMapping("/hello")
public class HelloController {

    @GetMapping
    public String index(){

       int count = DbBuilder.getCount("select count(*) from book");

       return "hello world" + count;
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasRole('USER')")
    public    Map<String, Object> index1(@PathVariable String id){

        Map<String, Object> obj = DbBuilder.getFirstRowMap("select * from user where id=" + id);

        return obj;
    }

    @GetMapping("/h2")
    public List<Map<String, Object>> index2(){

        Connection conn = DbBuilder.getConnection("spring.datasource.url","spring.datasource.username",
                "spring.datasource.password","spring.datasource.driver-class-name");

        List<Map<String, Object>> users = DbBuilder.getListMap(conn,"select * from book");

        DbBuilder.close(conn);

        return users;
    }

    @GetMapping("/h3")
    public ResponseEntity<?> index3(){

        return ResponseEntity
                .ok(new PaginatedResult()
                        .setData(DbBuilder.getListMap("select * from book"))
                        .setCurrentPage(1)
                        .setTotalPage(2));
    }

}
